<script setup>
import { ref, onMounted } from 'vue'
import { Picture,Edit } from '@element-plus/icons-vue'

import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {router} from "@/router/index.js";

const types = ref([])
const typeId = ref()


const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 查询表单
const searchForm = ref({
  name: '',
  goodsNum: '',
  category: '',
  typeId: '',
  minPrice: null,
  maxPrice: null,
  minStock: null,
  maxStock: null,
  startDate: '',
  endDate: ''
})

// 高级筛选
const showAdvanced = ref(false)



// 商品列表数据
const productList = ref([])


// 选中的商品
const selectedProducts = ref([])


const getGoodsType = ()=>{
  axios.get(`/goodsType/getGoodsTypes`).then(resp=>{
    types.value=resp.data
  })
}

// 获取分类名称
const getCategoryName = (category) => {
  const map = {
    'smart-band': '智能手环',
    'smart-watch': '智能手表',
    'health-monitor': '健康监测'
  }
  return map[category] || category
}

// 获取分类标签类型
const getCategoryTagType = (category) => {
  const map = {
    'smart-band': '',
    'smart-watch': 'success',
    'health-monitor': 'warning'
  }
  return map[category] || 'info'
}

// 获取状态名称
const getStatusName = (typeId) => {
  const type = types.value.find(t => t.id == typeId)
  return type ? type.name : `未知状态(${typeId})`

}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    'published': 'success',
    'unpublished': 'danger',
    'pending': 'warning',
    'rejected': 'info'
  }
  return map[status] || ''
}

// 状态筛选变化
const initData = (id) => {
  axios.get(`/goods/getGoodsByType/${id}/${currentPage.value}/${pageSize.value}`).then(resp =>{
    productList.value = resp.data.data;
    total.value = resp.data.total;
  })
}


// 重置查询条件
const resetSearch = () => {
  searchForm.value = {
    name: '',
    goodsNum: '',
    category: '',
    typeId: '',
    minPrice: null,
    maxPrice: null,
    minStock: null,
    maxStock: null,
    startDate: '',
    endDate: ''
  }
  currentPage.value = 1
  handleSearch()
}
const loading = ref(false)
// 查询
const handleSearch = async () => {
  try {
    loading.value = true

    // 构建查询参数
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm.value
    }

    // 过滤掉空值参数
    const filteredParams = Object.fromEntries(
        Object.entries(params).filter(([_, v]) => v !== '' && v !== null))

    const response = await axios.post('/goods/selectGoods', filteredParams)

    productList.value = response.data.data || response.data
    total.value = response.data.total || response.data.length

    ElMessage.success('查询成功')
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
const applyAdvancedSearch = () => {
  handleSearch();
  showAdvanced.value = false;
}
const options = ref([])
const selectCategoryName = ()=>{
  axios.get(`/category/getCategoryName`).then(resp=>{
    options.value = resp.data;
  })
}

// 批量操作 - 选择变化
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection
}

// 新增商品
const handleAdd = () => {
  router.push('/addGoods')
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  ElMessageBox.confirm('确定要删商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedProducts.value.map(item => item.id).join(',')
    axios.delete(`/goods/deleteGoodsByIds/${ids}`).then(resp => {
      ElMessage.success(resp.data)
      initData(typeId.value) // 刷新列表
    })
  })
}

// 批量上架
const handleBatchPublish = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  // 提取选中商品的ID数组
  const ids = selectedProducts.value.map(item => item.id).join(',')

  axios.put(`/goods/upGoodsByIds/${ids}`)
      .then(resp => {
        ElMessage.success(resp.data)
        initData(typeId.value) // 刷新列表
      })
      .catch(error => {
        ElMessage.error('上架失败')
        console.error('上架错误:', error)
      })
}

// 批量下架
const handleBatchUnpublish = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  // 提取选中商品的ID数组

  const ids = selectedProducts.value.map(item => item.id).join(',')

  axios.delete(`/goods/removeGoodsByIds/${ids}`)
      .then(resp => {
        ElMessage.success(resp.data)
        initData(typeId.value) // 刷新列表
      })
      .catch(error => {
        ElMessage.error('下架失败')
        console.error('下架错误:', error)
      })
}

const isLook = ref(true)

// 查看商品
const handleView = (row) => {
 router.push({path:'addGoods',query:{id:row.id,isLook:isLook.value}})
  // 这里可以跳转到详情页面
}

// 编辑商品
const handleEdit = (row) => {
  router.push(`addGoods?id=${row.id}`)
}

// 删除商品
const handleDelete = (row) => {
 axios.delete(`/goods/deleteGoodsByIds/${row.id}`).then(resp => {
   ElMessage.success(resp.data)
 })
}


const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  initData(typeId.value);

}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  initData(typeId.value);
}

// 库存编辑相关状态
const inventoryDialogVisible = ref(false)
const currentProduct = ref(null)
const inventoryForm = ref({
  inventory: 0,
  inventoryWarn: 0
})

// 打开库存编辑弹窗
const openInventoryDialog = (row) => {
  currentProduct.value = row
  inventoryForm.value = {
    inventory: row.inventory,
    inventoryWarn: row.inventoryWarn
  }
  inventoryDialogVisible.value = true
}

// 保存库存修改
const saveInventory = () => {
  axios.put(`/goods/updateInventory/${currentProduct.value.id}`, inventoryForm.value, ).then(resp => {
    ElMessage.success(resp.data)
    // 更新本地数据
    currentProduct.value.inventory = inventoryForm.value.inventory
    if (currentProduct.value.inventoryWarn !== undefined) {
      currentProduct.value.inventoryWarn = inventoryForm.value.inventoryWarn
    }
    initData(typeId.value);
    inventoryDialogVisible.value = false
  }).catch(error => {
    ElMessage.error('库存更新失败')
    console.error(error)
  })
}


// 初始化加载数据
onMounted(() => {
  getGoodsType();
  typeId.value = '0';
  selectCategoryName();
  initData(typeId.value);
})
</script>

<template>
  <div class="product-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h3>商品管理</h3>
        </div>
      </template>

      <!-- 状态筛选 -->
      <div class="status-filter">
        <el-radio-group v-model="typeId" @change="initData">
          <el-radio-button
              v-for="t in types"
              :key="t.id"
              :label="t.id"
          >
            {{ t.name }}
          </el-radio-button>
        </el-radio-group>
      </div>

      <el-divider />

      <!-- 查询条件 -->
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品名称">
              <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品编码">
              <el-input v-model="searchForm.goodsNum" placeholder="请输入商品编码" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品分类">
              <el-select
                  v-model="searchForm.category"
                  placeholder="请选择分类"
                  clearable
              >
                <el-option
                    v-for="item in options"
                    :key="item"
                    :label="item"
                    :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品类型">
              <el-select
                  v-model="searchForm.typeId"
                  placeholder="请选择类型"
                  clearable
              >
                <el-option
                    v-for="type in types"
                    :key="type.id"
                    :label="type.name"
                    :value="type.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      <!-- 高级筛选弹窗 -->
        <el-collapse-transition>
          <div v-if="showAdvanced">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="最低价格">
                  <el-input-number
                      v-model="searchForm.minPrice"
                      :min="0"
                      :precision="2"
                      controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="最高价格">
                  <el-input-number
                      v-model="searchForm.maxPrice"
                      :min="0"
                      :precision="2"
                      controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="最低库存">
                  <el-input-number
                      v-model="searchForm.minStock"
                      :min="0"
                      controls-position="right"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="最高库存">
                  <el-input-number
                      v-model="searchForm.maxStock"
                      :min="0"
                      controls-position="right"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="开始日期">
                  <el-date-picker
                      v-model="searchForm.startDate"
                      type="date"
                      placeholder="选择开始日期"
                      value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="结束日期">
                  <el-date-picker
                      v-model="searchForm.endDate"
                      type="date"
                      placeholder="选择结束日期"
                      value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
        <el-form-item class="form-actions">
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="text" @click="showAdvanced = !showAdvanced">
            {{ showAdvanced ? '隐藏高级查询' : '显示高级查询' }}
          </el-button>
        </el-form-item>
      </el-form>


      <!-- 批量操作 -->
      <div class="batch-actions">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleBatchDelete">删除</el-button>
        <el-button type="success" @click="handleBatchPublish">上架</el-button>
        <el-button type="warning" @click="handleBatchUnpublish">下架</el-button>
      </div>

      <!-- 商品列表 -->
      <el-table
          :data="productList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="商品ID" width="100" />
        <el-table-column prop="name" label="商品名称" width="150" />
        <el-table-column prop="category" label="商品分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)">
              {{ getCategoryName(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="商品图片" width="150">
          <template #default="{ row }">
            <el-image
                style="width: 100px; height: 100px"
                :src="row.image"
                :preview-src-list="[row.image]"
                fit="cover"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="商品标题" width="200" />
        <el-table-column prop="goodsNum" label="商品编码" width="120" />
        <el-table-column prop="price" label="商品价格" width="120">
          <template #default="{ row }">
            {{ row.price }}¥
          </template>
        </el-table-column>
        <el-table-column prop="inventory" label="库存" width="150">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; gap: 8px">
              <span>{{ row.inventory }}</span>
              <el-button
                  type="primary"
                  :icon="Edit"
                  circle
                  size="small"
                  @click="openInventoryDialog(row)"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="typeId" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.typeId)">
              {{ getStatusName(row.typeId) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 库存编辑弹窗 -->
      <el-dialog
          v-model="inventoryDialogVisible"
          title="编辑库存"
          width="500px"
      >
        <el-form :model="inventoryForm" label-width="100px">
          <el-form-item label="商品编码">
            <span style="margin-left: 10px">{{ currentProduct?.goodsNum }}</span>
          </el-form-item>
          <el-form-item label="商品名称">
            <span style="margin-left: 10px">{{ currentProduct?.name }}</span>
          </el-form-item>
          <el-form-item label="商品标题">
            <span style="margin-left: 10px">{{ currentProduct?.title }}</span>
          </el-form-item>
          <el-divider />
          <el-form-item label="商品库存" prop="inventory">
            <el-input-number
                v-model="inventoryForm.inventory"
                :min="0"
                controls-position="right"
                style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="库存预警" prop="inventoryWarn">
            <el-input-number
                v-model="inventoryForm.inventoryWarn"
                :min="0"
                controls-position="right"
                style="width: 200px"
            />
          </el-form-item>
        </el-form>
        <template #footer>
    <span class="dialog-footer">
      <el-button @click="inventoryDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveInventory">确定</el-button>
    </span>
        </template>
      </el-dialog>


      <!-- 分页 -->
      <div class="pagination" >
        <ElPagination
            :current-page="currentPage"
            :page-size="pageSize"
            :page-sizes="[3, 10, 30, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.product-management {
  padding: 20px;
}

.card-header {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.status-filter {
  margin-bottom: 20px;
}

.search-conditions {
  margin-bottom: 20px;
}

.advanced-search {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 10px;
}

.price-separator {
  margin: 0 10px;
  color: #909399;
}

.batch-actions {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

/* 库存编辑按钮样式 */
.el-button--primary.is-circle {
  margin-left: 8px;
}

/* 弹窗表单样式 */
.el-form-item__content span {
  color: #606266;
}

/* 弹窗标题样式 */
.el-dialog__title {
  font-size: 18px;
  font-weight: bold;
}

/* 弹窗分割线样式 */
.el-divider {
  margin: 10px 0;
}

/* 表单标签样式 */
.el-form-item__label {
  font-weight: bold;
}
.search-conditions {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.search-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.search-form-item :deep(.el-form-item__label) {
  width: 80px;
  text-align: right;
  padding-right: 10px;
  color: #606266;
  font-weight: normal;
}

.search-input {
  width: 180px;
}

.search-select {
  width: 180px;
}

.search-button {
  padding: 9px 15px;
}

.advanced-button {
  margin-left: 10px;
  padding: 9px 5px;
}

/* 高级筛选样式 */
.advanced-search {
  margin-top: 15px;
  padding: 15px;
  background-color: #f0f2f5;
  border-radius: 4px;
}

.advanced-form-item {
  margin-bottom: 0;
  display: flex;
  align-items: center;
}

.advanced-form-item :deep(.el-form-item__label) {
  width: 80px;
  text-align: right;
  padding-right: 10px;
  color: #606266;
  font-weight: normal;
}

.advanced-input {
  width: 120px;
}

.advanced-date-picker {
  width: 280px;
}

.price-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

/* 调整下拉框内部样式 */
.search-select :deep(.el-input__inner),
.advanced-input :deep(.el-input__inner) {
  height: 32px;
  line-height: 32px;
}

/* 调整按钮样式 */
.search-button {
  height: 32px;
  padding: 7px 15px;
}

/* 状态筛选样式调整 */
.status-filter {
  margin-bottom: 20px;
  padding: 10px 0;
}

.status-filter :deep(.el-radio-button__inner) {
  padding: 10px 15px;
}

.advanced-dialog {
  .el-dialog__body {
    padding: 20px;
  }

  .el-form-item {
    margin-bottom: 18px;
  }

  .el-date-editor {
    width: 100%;
  }

  .el-input-number {
    width: 100%;
  }
}

/* 调整弹窗按钮样式 */
.dialog-footer {
  .el-button {
    padding: 10px 20px;
  }
}
</style>